package com.xchb.im.common.utils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author XDD
 * @project muchat
 * @date 2021/7/16
 * @description Good Good Study,Day Day Up.
 */
public class SingleUtils {

    private final static Map<String, Object> map = new ConcurrentHashMap<>(5);

    private SingleUtils() {
        //防止反射调用
        throw new RuntimeException("此单例类不允许发射调用");
    }

    public static <T> T getInstance(Class<T> tClass) {
        Object obj = map.get(tClass.getName());
        if (obj != null) {
            return tClass.cast(obj);
        }

        synchronized (tClass) {
            try {
                obj = map.get(tClass.getName());
                if(obj==null){
                    obj = tClass.newInstance();
                    map.put(tClass.getName(), obj);
                    return tClass.cast(obj);
                }
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return tClass.cast(obj);
    }


    public static void main(String[] args) {
        for (int i = 0; i <= 10; i++) {
            new Thread(() -> {
                System.out.println(getInstance(SingleUtils.class));
            }).start();
        }
    }
}
